package com.yupi.springbootinit.service.workflow;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.mapper.WorkflowTaskMapper;
import com.yupi.springbootinit.model.entity.WorkflowTask;
import com.yupi.springbootinit.model.vo.DepartmentTaskStatsVO;
import com.yupi.springbootinit.model.vo.PersonalTaskStatsVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.yupi.springbootinit.service.workflow.WorkflowTaskConstants.*;

/**
 * 工作流任务统计服务
 */
@Slf4j
@Service
public class WorkflowTaskStatisticsService {

    @Resource
    private WorkflowTaskMapper workflowTaskMapper;

    /**
     * 获取部门任务统计
     */
    public DepartmentTaskStatsVO getDepartmentTaskStats(Long departmentId) {
        if (departmentId == null) {
            return createEmptyStats(departmentId);
        }

        // 统计所有任务（包括子任务）
        Long total = countByDepartmentAndStatus(departmentId, null);
        Long pending = countByDepartmentAndStatus(departmentId, STATUS_PENDING);
        Long inProgress = countByDepartmentAndStatus(departmentId, STATUS_IN_PROGRESS);
        Long completed = countByDepartmentAndStatus(departmentId, STATUS_DONE);

        // 创建统计结果
        DepartmentTaskStatsVO stats = new DepartmentTaskStatsVO();
        stats.setDepartmentId(departmentId);
        stats.setTotal(total);
        stats.setPending(pending);
        stats.setInProgress(inProgress);
        stats.setCompleted(completed);
        stats.setUpdatedAt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        // 设置分布数据
        List<DepartmentTaskStatsVO.Item> distribution = Arrays.asList(
            new DepartmentTaskStatsVO.Item("待处理", pending),
            new DepartmentTaskStatsVO.Item("进行中", inProgress),
            new DepartmentTaskStatsVO.Item("已完成", completed)
        );
        stats.setDistribution(distribution);

        return stats;
    }

    /**
     * 统计部门任务数量（按状态）
     */
    private Long countByDepartmentAndStatus(Long departmentId, String status) {
        QueryWrapper<WorkflowTask> qw = new QueryWrapper<>();
        qw.eq("departmentId", departmentId)
          .ne("taskType", TASK_TYPE_PUBLISH_BATCH) // 仅统计父任务，排除PMC子任务（发布版次）
          .eq("isDelete", 0);
          
        if (status != null) {
            qw.eq("taskStatus", status);
        }
        
        return workflowTaskMapper.selectCount(qw);
    }

    /**
     * 创建空的统计结果
     */
    private DepartmentTaskStatsVO createEmptyStats(Long departmentId) {
        DepartmentTaskStatsVO stats = new DepartmentTaskStatsVO();
        stats.setDepartmentId(departmentId);
        stats.setTotal(0L);
        stats.setPending(0L);
        stats.setInProgress(0L);
        stats.setCompleted(0L);
        stats.setUpdatedAt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        List<DepartmentTaskStatsVO.Item> distribution = Arrays.asList(
            new DepartmentTaskStatsVO.Item("待处理", 0L),
            new DepartmentTaskStatsVO.Item("进行中", 0L),
            new DepartmentTaskStatsVO.Item("已完成", 0L)
        );
        stats.setDistribution(distribution);

        return stats;
    }

    /**
     * 获取个人任务统计
     */
    public PersonalTaskStatsVO getPersonalTaskStats(Long userId) {
        if (userId == null) {
            PersonalTaskStatsVO stats = new PersonalTaskStatsVO();
            stats.setPending(0L);
            stats.setCompleted(0L);
            return stats;
        }

        // 1. 查询所有任务
        QueryWrapper<WorkflowTask> allQw = new QueryWrapper<>();
        allQw.eq("claimedBy", userId)
                .eq("isDelete", 0);
        List<WorkflowTask> allTasks = workflowTaskMapper.selectList(allQw);

        // 2. 找出所有有子任务的父任务ID
        Set<Long> parentIdsWithChildren = allTasks.stream()
                .filter(t -> t.getParentTaskId() != null)
                .map(WorkflowTask::getParentTaskId)
                .collect(Collectors.toSet());

        // 3. 过滤出叶子节点任务（无子任务的父任务 + 所有子任务）
        List<WorkflowTask> leafTasks = allTasks.stream()
                .filter(t -> {
                    // 如果是父任务且有子任务，则不统计
                    if (t.getParentTaskId() == null && parentIdsWithChildren.contains(t.getId())) {
                        return false;
                    }
                    return true;
                })
                .collect(Collectors.toList());

        // 4. 统计各状态数量
        long pending = leafTasks.stream()
                .filter(t -> STATUS_PENDING.equals(t.getTaskStatus()) || STATUS_IN_PROGRESS.equals(t.getTaskStatus()))
                .count();

        long completed = leafTasks.stream()
                .filter(t -> STATUS_COMPLETED.equals(t.getTaskStatus()) || STATUS_DONE.equals(t.getTaskStatus()))
                .count();

        PersonalTaskStatsVO stats = new PersonalTaskStatsVO();
        stats.setPending(pending);
        stats.setCompleted(completed);

        log.info("个人任务统计（叶子节点）: userId={}, 未完成={}, 已完成={}, 总叶子节点={}",
                userId, pending, completed, leafTasks.size());

        return stats;
    }


    /**
     * 统计个人任务数量（按状态）
     */
    private Long countByUserAndStatus(Long userId, String status) {
        QueryWrapper<WorkflowTask> qw = new QueryWrapper<>();
        qw.eq("claimedBy", userId)
          .ne("taskType", TASK_TYPE_PUBLISH_BATCH) // 仅统计父任务，排除PMC子任务（发布版次）
          .eq("isDelete", 0);
          
        if (status != null) {
            qw.eq("taskStatus", status);
        }
        
        return workflowTaskMapper.selectCount(qw);
    }

    /**
     * 创建空的个人统计结果
     */
    private PersonalTaskStatsVO createEmptyPersonalStats(Long userId) {
        PersonalTaskStatsVO stats = new PersonalTaskStatsVO();
        stats.setUserId(userId);
        stats.setTotal(0L);
        stats.setPending(0L);   // 未完成(IN_PROGRESS)
        stats.setCompleted(0L); // 已完成(DONE)
        stats.setOverdue(0L);
        stats.setUpdatedAt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        PersonalTaskStatsVO.Item i1 = new PersonalTaskStatsVO.Item(); i1.setType("未完成"); i1.setCount(0L); i1.setColor("#faad14");
        PersonalTaskStatsVO.Item i2 = new PersonalTaskStatsVO.Item(); i2.setType("已完成"); i2.setCount(0L); i2.setColor("#52c41a");
        stats.setDistribution(Arrays.asList(i1, i2));
        return stats;
    }
}